<template>
  <div class="app-container">
    <el-form :model="queryParams"
             ref="queryForm"
             size="small"
             :inline="true"
             v-show="showSearch"
             label-width="100px">
      <el-form-item label="设备序列号"
                    prop="machineCode">
        <el-input v-model="queryParams.machineCode"
                  placeholder="请输入设备序列号"
                  clearable
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="医疗机构名称"
                    prop="medicalIdName">
        <el-input v-model="queryParams.medicalIdName"
                  placeholder="请输入医疗机构名称"
                  clearable
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   icon="el-icon-search"
                   size="mini"
                   @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"
                   size="mini"
                   @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10"
            class="mb8">
      <el-col :span="1.5">
        <el-button type="primary"
                   plain
                   icon="el-icon-plus"
                   size="mini"
                   @click="handleAdd"
                   v-hasPermi="['system:machine:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success"
                   plain
                   icon="el-icon-edit"
                   size="mini"
                   :disabled="single"
                   @click="handleUpdate"
                   v-hasPermi="['system:machine:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger"
                   plain
                   icon="el-icon-delete"
                   size="mini"
                   :disabled="multiple"
                   @click="handleDelete"
                   v-hasPermi="['system:machine:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning"
                   plain
                   icon="el-icon-download"
                   size="mini"
                   @click="handleExport"
                   v-hasPermi="['system:machine:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch"
                     @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              :data="machineList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection"
                       width="55"
                       align="center" />
      <el-table-column label="序号"
                       align="center"
                       prop="id" />
      <el-table-column label="编码"
                       align="center"
                       prop="machineCode" />
      <el-table-column label="网络状态"
                       align="center"
                       prop="networkStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.machine_network_status"
                    :value="scope.row.networkStatus" />
        </template>
      </el-table-column>
      <el-table-column label="运行状态"
                       align="center"
                       prop="runningStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.equipment_run_status"
                    :value="scope.row.runningStatus" />
        </template>
      </el-table-column>
      <el-table-column label="运行时间"
                       align="center"
                       prop="runtime"
                       :formatter="formartRunTime" />
      <el-table-column label="机构名称"
                       align="center"
                       prop="medicalIdName" />
      <el-table-column label="处理污水量(升)"
                       align="center"
                       prop="sewagel" />
      <el-table-column label="处理污水量(吨)"
                       align="center"
                       prop="sewaget" />
      <el-table-column label="纯净水缺水"
                       align="center"
                       prop="clearwaterlow" />
      <el-table-column label="设备PH值"
                       align="center"
                       prop="machinePh" />
      <el-table-column label="设备COD值"
                       align="center"
                       prop="machineCod" />
      <el-table-column label="设备氨氮值"
                       align="center"
                       prop="machineAy" />
      <el-table-column label="操作"
                       align="center"
                       class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:freshMachine:edit']">修改</el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-view"
                     @click="handleView(scope.row,scope.index)"
                     v-hasPermi="['system:freshMachine:query']">详情</el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleDelete(scope.row)"
                     v-hasPermi="['system:freshMachine:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList" />

    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title"
               :visible.sync="open"
               width="500px"
               append-to-body>
      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="80px">
        <el-form-item label="序号"
                      prop="serial">
          <el-input v-model="form.serial"
                    placeholder="请输入设备序号" />
        </el-form-item>
        <el-form-item label="设备编码"
                      prop="machineCode">
          <el-input v-model="form.machineCode"
                    placeholder="请输入设备编码" />
        </el-form-item>
        
        <el-form-item label="机构查询">
          <el-tree
            class="tree-border"
            :data="deptOptions"
            @node-click="deptOptionsClick"
            default-expand-all
            ref="dept"
            node-key="id"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="机构名称"
                      prop="institutionId">
          <el-select v-model="form.institutionId"
                     placeholder="请选择机构"
                     style="width: 370px">
            <el-option v-for="item in institutionOptions"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"
                       ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运维码"
                      prop="opCode">
          <el-upload ref="upload"
                     :limit="1"
                     drag
                     class="avatar-uploader uploadMt"
                     :show-file-list="false"
                     action="#"
                     :multiple="false"
                     :http-request="updateOpcodeImg">
            <img v-if="opCodeImg"
                 :src="opCodeImg"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备详细 -->
    <el-dialog :title="title"
               :visible.sync="viewOpen"
               width="800px"
               append-to-body>
      <el-form ref="form"
               :model="form"
               label-width="100px"
               size="mini">
        <div class="flex">
          <el-row>
            <el-col :span="12">
              <el-form-item label="序号">{{form.serial}}</el-form-item>
              <el-form-item label="设备编码：">{{form.machineCode}}</el-form-item>
              <el-form-item label="网络状态：">
                <template>
                  <dict-tag :options="dict.type.machine_network_status"
                            :value="form.networkStatus" />
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备状态：">
                <template>
                  <dict-tag :options="dict.type.equipment_run_status"
                            :value="form.runningStatus" />
                </template>
              </el-form-item>
              <el-form-item label="机构名称">{{ form.medicalIdName }}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="处理污水量(升)：">{{ form.sewagel }}</el-form-item>
              <el-form-item label="处理污水量(吨)：">{{ form.sewaget }}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经度：">{{ form.longitude }}</el-form-item>
              <el-form-item label="维度：">{{ form.dimension }}</el-form-item>
            </el-col>
           </el-row>
           <el-form-item label="运维码">
              <template>
                <img 
                  style="width:200px;"
                 :src="opCodeImg"
                 class="avatar">
              </template>
            </el-form-item>
        </div>
      </el-form>
      <div class="line-h p-tb-10">
         <div class="view-title">上报记录</div>
          <el-table v-loading="loading"
              :data="institutionList">
            <el-table-column label="序号" align="center" prop="id" />
            <el-table-column label="设备运行状态" align="center" prop="onoff">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.equipment_run_status" :value="scope.row.onoff"/>
              </template>
            </el-table-column>
            <el-table-column label="设备编码" align="center" prop="code" />
            <el-table-column label="污水处理量(升)" align="center" prop="sewagel" />
            <el-table-column label="污水处理量(吨)" align="center" prop="sewaget" />
            <el-table-column label="吸污泵运行状态" align="center" prop="inpumponoff">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.equipment_run_status" :value="scope.row.inpumponoff"/>
              </template>
            </el-table-column>
            <el-table-column label="排污泵运行状态" align="center" prop="outpumponoff">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.equipment_run_status" :value="scope.row.outpumponoff"/>
              </template>
            </el-table-column>
            <el-table-column label="臭氧模块运行状态" align="center" prop="ozoneonoff">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.equipment_run_status" :value="scope.row.ozoneonoff"/>
              </template>
            </el-table-column>
            <el-table-column label="循环泵运行状态" align="center" prop="sterilizetime">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.equipment_run_status" :value="scope.row.sterilizetime"/>
              </template>
            </el-table-column>
            <el-table-column label="纯净水缺水指示位" align="center" prop="clearwaterlow" />
            <el-table-column label="纯净水水位高指示位" align="center" prop="clearwaterhigh" />
            <el-table-column label="远程控制停止位" align="center" prop="onoffwrite" />
            <el-table-column label="吸污泵运行超时报警位" align="center" prop="xiwubengbaojing" />
            <el-table-column label="排污泵运行超时报警位" align="center" prop="paiwubengbaojing" />
            <el-table-column label="报警时间" align="center" prop="baojingtime" :formatter="formartData" />
            <el-table-column label="设备运行时间" align="center" prop="runtime" :formatter="formartRunTime"/>
            <el-table-column label="经度" align="center" prop="longitude" />
            <el-table-column label="维度" align="center" prop="dimension" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:log:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
                </el-table>
                <pagination
                  v-show="totalLog>0"
                  :total="totalLog"
                  :page.sync="queryParamsLog.pageNum"
                  :limit.sync="queryParamsLog.pageSize"
                  @pagination="getListLog"
                />
      </div>
      <div class="line-h p-tb-10">
         <div class="view-title">检测值信息</div>
          <el-table v-loading="loading"
                    :data="Dayhandlelist">
            <el-table-column label="序号"
                             align="center"
                             prop="id" />
            <el-table-column label="处理污水量（升）"
                             align="center"
                             prop="sewagel" />
           <el-table-column label="处理污水量（吨）"
           align="center"
           prop="sewaget" />
          </el-table>
          </el-table-column>
                </el-table>
                <pagination
                  v-show="Dayhandlelisttotal>0"
                  :total="Dayhandlelisttotal"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getListDayhandlelist"
                />
      </div>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMachine, getMachine, delMachine, addMachine, updateMachine,dayHandleList } from "@/api/system/freshMachine";
import { uploadAvatar } from "@/api/system/user";
import { listInstitution,getInsoption } from "@/api/system/institution";
import { treeselect } from "@/api/system/dept";
import { listLog, delLog} from "@/api/system/log";
import { prodReportList } from "@/api/system/report";
export default {
  dicts: ['equipment_run_status', 'equipment_bj_status', 'machine_network_status'],
  name: "FreshMachine",
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "label"
      },
       // 部门列表
      deptOptions: [],
      //上报记录
      institutionList:[],
      // 总条数
      total: 0,
      //运维码图片
      opCodeImg:null,
      totalLog:0,
      //处理量总数
      Dayhandlelisttotal:0,
      //处理量列表
      Dayhandlelist:[],
      // 遮罩层
      loading: true,
      //设备编号
      code:null,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备信息表格数据
      machineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      viewOpen: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        machineCode: null,
        medicalIdName: null
      },
      //详情日志列表查询参数
      queryParamsLog:{
        pageNo: 1,
        pageSize: 10,
        machineCode: null,
        medicalIdName: null
      },
      //详情处理量列表查询参数
      queryParamsDayhandlelist:{
        pageNo: 1,
        pageSize: 10,
        machineCode: null,
        medicalIdName: null
      },
      institutionOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        machineCode: [
          { required: true, message: "设备编码不能为空", trigger: "blur" }
        ],
        institutionId: [
          { required: true, message: "所属机构不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    //查询结构列表
    deptOptionsClick(res){
      getInsoption({deptId:res.id}).then(response => {
        this.institutionOptions = response.data;
      });
    },
    formartData(data){
      let date = new Date(Number(data.baojingtime));
      let Y = date.getFullYear() + '-';
      let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
      let D = date.getDate() + ' ';
      let h = date.getHours() + ':';
      let m = date.getMinutes() + ':';
      let s = date.getSeconds(); 
      return Y+M+D+h+m+s;
    },
  // 上传运维码
    updateOpcodeImg(params, type) {
      let file = params.file
      let vm = this;
      const formdata = new FormData();
      formdata.append("avatarfile", file);
      uploadAvatar(formdata).then(response => {
        this.form.opCode = response.imgUrl;
        this.opCodeImg = process.env.VUE_APP_BASE_API + response.imgUrl;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备上报日志编号为"' + ids + '"的数据项？').then(function() {
        return delLog(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 查询设备信息列表 */
    getList() {
      this.loading = true;
      listMachine(this.queryParams).then(response => {
        this.machineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    formartRunTime(data) {
      let runtime = JSON.parse(data.runtime);
      if (runtime === null) {
        return runtime;
      }
      return runtime[0] + " 天" + runtime[1] + "小时" + runtime[2] + "分" + runtime[3] + "秒";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    getListLog(){
      this.loading = true;
      this.queryParamsLog.code = this.code
      listLog(this.queryParamsLog).then(response => {
        this.institutionList = response.rows;
        this.loading = false;
        this.totalLog = response.total;
      });
    },
    getListDayhandlelist(){
      this.loading = true;
      this.queryParamsDayhandlelist.institutionId = this.code
      prodReportList(this.queryParamsDayhandlelist).then(response => {
        this.Dayhandlelist = response.rows;
        this.loading = false;
        this.Dayhandlelisttotal = response.total;
      });
    },
    handleView(row) {
      this.viewOpen = true;
      this.form = row;
      this.code = row.machineCode
      this.title = "设备编号" + row.machineCode + "详情";
      this.getListLog()
      this.getListDayhandlelist()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        machineCode: null,
        medicalIdName: null
      };
      this.opCodeImg = null
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备信息";
      listInstitution({ pageNum: 1, pageSize: 100 }).then(response => {
        this.institutionOptions = response.rows;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMachine(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备信息";
        this.opCodeImg = response.data.opCode ? process.env.VUE_APP_BASE_API + response.data.opCode : null
      });
      listInstitution({ pageNum: 1, pageSize: 100 }).then(response => {
        this.institutionOptions = response.rows;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMachine(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMachine(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备信息编号为"' + ids + '"的数据项？').then(function () {
        return delMachine(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/freshMachine/export', {
        ...this.queryParams
      }, `machine_${new Date().getTime()}.xlsx`)
    },
    // /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
        console.log(this.deptOptions)
      });
    },
  }
};
</script>
<style>
  .uploadMt .el-upload-dragger {
    width: 200px;
    height: 200px;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
}

.el-upload-dragger img{
  width:200px;
  height:200px;
}
</style>